package no.uio.ifi.cop.common;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Map;

/**
 * Commonly used functions.
 *
 * @version 1.0
 * @author  bjarneh@ifi.uio.no
 */


public class Common{

    // read all the content of a text-file into a String
    public static String slurp(String filepath) throws IOException{

        File file = new File(filepath);

        if(! file.isFile()){
            Log.fatal("%s - is not a file", filepath);
        }

        if( file.isDirectory() ){
            Log.fatal("%s - is directory", filepath);
        }

        if(! file.canRead()){
            Log.fatal("%s - you don't have read access", filepath);
        }

        FileReader fr = new FileReader(file);
        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[1024];
        int n;

        while( (n = fr.read(buffer, 0, 1024)) != -1 ){
            sb.append(buffer, 0, n);
        }

        return sb.toString();
    }

    // opposite of slurp, write String to a path
    public static void spit(String where, String what) throws IOException{
        FileWriter fileWriter = new FileWriter( where );
        BufferedWriter bufferedWriter = new BufferedWriter( fileWriter );
        bufferedWriter.write( what );
        bufferedWriter.close();
    }

    // note: startComment cannot be meta-character in regex
    // these three starters are safe: #  (hash),  %  (percent)  ;  (semicolon)
    public static String stripComment(char startComment, String content){
        Pattern pattern = Pattern.compile(startComment + "[^\n]+");
        Matcher matcher = pattern.matcher(content);
        return matcher.replaceAll("");
    }

    // same as Unix command: which("command") => path/to/command||null
    public static String which(String cmd){
        File file;
        Map<String, String> env = System.getenv();
        String path = env.get("PATH");
        if(path == null){ return null; }
        String[] dirs = path.split(File.pathSeparator);
        for(String d : dirs){
            file = new File(d, cmd);
            if(file.exists() && file.canExecute()){
                return file.getAbsolutePath();
            }
        }
        return null;
    }

}
